<template>
  <!-- 班制表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="900px"
      height="600px"
      style="max-height: 800px"
      draggable
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="formData" :inline="true" :rules="rules">
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div class="search-container">
          <el-row>
            <el-col :span="12">
              <el-form-item label="班制编号" prop="shiftSetCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.shiftSetCode"
                  placeholder="请输入班制编号"
                  clearable
                />
                <span v-else>{{ formData.shiftSetCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班制名称" prop="shiftSetName">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.shiftSetName"
                  placeholder="请输入班制名称"
                  clearable
                />
                <span v-else>{{ formData.shiftSetName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="工厂" prop="plantCode" label-width="71">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.plantCode"
                  placeholder="请选择所在工厂"
                  clearable
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="item in plantList"
                    :key="item.id"
                    :label="item.organizationCode"
                    :value="item.organizationCode"
                  />
                </el-select>

                <span v-else>{{ formData.plantCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12"
              ><el-form-item label="备注" prop="remarks" label-width="71">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  clearable
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item></el-col
            >
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="默认数据" prop="enabled">
                <el-radio-group
                  v-model="formData.isDefault"
                  v-if="!props.isReadonly"
                >
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
                <span v-else>{{ formData.isDefault == 1 ? "是" : "否" }}</span>
              </el-form-item></el-col
            >
            <el-col :span="12">
              <el-form-item label="是否启用" prop="enabled">
                <el-radio-group
                  v-model="formData.enabled"
                  v-if="!props.isReadonly"
                >
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">停用</el-radio>
                </el-radio-group>
                <span v-else>{{
                  formData.enabled == 1 ? "启用" : "停用"
                }}</span>
              </el-form-item></el-col
            >
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button
              type="success"
              plain
              @click="handleAdd"
              v-if="!props.isReadonly"
            >
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <div class="formTable">
            <el-table
              :data="formData.details"
              :key="Math.random"
              border
              style="max-height: 200px; overflow: auto"
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="60"
              />
              <el-table-column
                label="班制顺序"
                props="sequenceCode"
                align="center"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.sequenceCode'"
                    :rules="rules.sonsequenceCode"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.sequenceCode"
                      placeholder="请输入班制顺序"
                      clearable
                      style="padding-top: 15px"
                    />
                    <span v-else>{{ row.sequenceCode }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="班次"
                props="shiftCode"
                min-width="150"
                align="center"
                style="padding-top: 15px"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.shiftCode'"
                    :rules="rules.sonshiftCode"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.shiftCode"
                      placeholder="请选择班次"
                      clearable
                      style="width: 100%; padding-top: 15px"
                      @change="messhiftChange($index, row.shiftCode)"
                      filterable
                    >
                      <el-option
                        v-for="item in messhiftValue"
                        :key="item.id"
                        :label="item.shiftCode ? item.shiftCode : ''"
                        :value="item.shiftCode ? item.shiftCode : ''"
                      />
                    </el-select>
                    <span v-else>{{ row.shiftCode }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="起始时间"
                props="timeBegin"
                min-width="150"
                align="center"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.timeBegin'"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.timeBegin"
                      placeholder="请选择班次"
                      clearable
                      disabled
                      style="padding-top: 15px"
                    />
                    <span v-else>{{ row.timeBegin }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="结束时间"
                props="timeBegin"
                min-width="150"
                align="center"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.timeEnd'"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.timeEnd"
                      placeholder="请选择班次"
                      clearable
                      disabled
                      style="padding-top: 15px"
                    />
                    <span v-else>{{ row.timeEnd }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

import { useDictionary } from "@/utils/useTable";
defineOptions({
  name: "MESMESSHIFTSETADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData: any = reactive({
  id: "",
  shiftSetCode: "",
  shiftSetName: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  isDefault: 0,
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  details: [
    {
      id: "",
      shiftSetId: "",
      sequenceCode: "",
      shiftId: "",
      shiftCode: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  shiftSetCode: [
    {
      required: true,
      pattern: "[^ \x20]+",
      message: "请输入班制编号",
      trigger: "blur",
    },
    { required: true, message: "请输入班制编号", trigger: "blur" },
  ],
  shiftSetName: [
    {
      required: true,
      pattern: "[^ \x20]+",
      message: "请输入班制名称",
      trigger: "blur",
    },
    { required: true, message: "请输入班制名称", trigger: "blur" },
  ],
  plantCode: [{ required: true, message: "请选择工厂", trigger: "change" }],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [{ required: true, message: "请输入是否启用", trigger: "blur" }],
  sonsequenceCode: [
    { required: true, message: "请输入班次顺序", trigger: "blur" },

    {
      validator: validateDegree,
      trigger: "blur",
    },
  ],

  sonshiftCode: [{ required: true, message: "请输入班次", trigger: "change" }],
});

function validateDegree(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else if (Number(value) > 100 || Number(value) <= 0) {
    callback(new Error("请输入1-100之间的数字"));
  } else {
    callback();
  }
}

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

const details: any = {
  id: "",
  shiftSetId: "",
  sequenceCode: "",
  shiftId: "",
  shiftCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      // plantReadOnlyFn();
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formData.details = [details];
  formData.id = "";
  formData.shiftSetCode = "";
  formData.shiftSetName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.isDefault = 0;
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
}

const loading = ref(false);

/** 班制保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/mes/messhiftset/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

const messhiftChange = (index: number, code: string) => {
  messhiftValue.value.forEach((item: any) => {
    //班次为空时清楚班次id，起始、截止时间
    if (!code) {
      formData.details[index].shiftId = "";
      formData.details[index].timeBegin = "";
      formData.details[index].timeEnd = "";
    }
    if (item.shiftCode == code) {
      formData.details[index].shiftId = item.id;
      formData.details[index].timeBegin = item.timeBegin;
      formData.details[index].timeEnd = item.timeEnd;
    }
  });
};
async function getdetails() {
  let sondetails = await request({
    url: "/mes/messhiftset/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

// 获取工厂列表
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
};
// 根据工厂id 查询班次
const messhiftValue: any = ref([]);
const messhiftList = async () => {
  if (formData.plantCode != "") {
    const res2: any = await request({
      url: `/mes/messhift/getList`,
      method: "post",
      data: { enabled: 1, plantId: formData.plantId },
    });
    messhiftValue.value = res2.data;
  } else {
    messhiftValue.value = [];
  }
};

/** 选择工厂时触发*/
watch(
  () => formData.plantCode,
  (newVal: any) => {
    formData.details = [
      {
        id: "",
        shiftSetId: "",
        sequenceCode: "",
        shiftId: "",
        shiftCode: "",
        version: "",
        remarks: "",
        createTime: "",
        createdUserId: "",
        createdUserName: "",
        lastUpdateTime: "",
        lastUpdatedUserId: "",
        lastUpdatedUserName: "",
        enabled: "",
        deleted: "",
      },
    ];
    plantList.value.forEach((item: any) => {
      if (item.organizationCode == formData.plantCode) {
        formData.plantId = item.id;
      }
    });
    messhiftList();
  }
);

// 输入框出发时

onMounted(() => {
  getPlantList();
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
}
:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
.isDeafutl {
  :deep(.el-form-item__label) {
    width: 130px !important;
  }
}
</style>
